import { createSlice } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'

export const counterSlice = createSlice({
    name: 'counter',
    initialState: {
        language: (typeof window !== 'undefined' && localStorage.getItem('language')) || 'en',
        theme: (typeof window !== 'undefined' && (localStorage.getItem('theme') as 'light' | 'dark')) || 'light'
    },
    reducers: {
        setLanguage(state, action: PayloadAction<'en' | 'zh'>) {
            state.language = action.payload
            if (typeof window !== 'undefined') {
                localStorage.setItem('language', action.payload)
            }
        },
        setTheme(state, action: PayloadAction<'light' | 'dark'>) {
            state.theme = action.payload
            if (typeof window !== 'undefined') {
                localStorage.setItem('theme', action.payload)
            }
        },
        toggleTheme(state) {
            state.theme = state.theme === 'dark' ? 'light' : 'dark'
            if (typeof window !== 'undefined') {
                localStorage.setItem('theme', state.theme)
            }
        },
    },
})

export const { setLanguage, setTheme, toggleTheme } = counterSlice.actions

export default counterSlice.reducer